var _api2 = _interopRequireDefault(require("../../../utils/api")), _eventEmitter = _interopRequireDefault(require("../../../utils/event-emitter")), _util = _interopRequireDefault(require("../../../utils/util"));

function _interopRequireDefault(t) {
    return t && t.__esModule ? t : {
        default: t
    };
}

function _slicedToArray(t, e) {
    return _arrayWithHoles(t) || _iterableToArrayLimit(t, e) || _nonIterableRest();
}

function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

function _iterableToArrayLimit(t, e) {
    var i = [], a = !0, n = !1, s = void 0;
    try {
        for (var r, o = t[Symbol.iterator](); !(a = (r = o.next()).done) && (i.push(r.value), 
        !e || i.length !== e); a = !0) ;
    } catch (t) {
        n = !0, s = t;
    } finally {
        try {
            a || null == o.return || o.return();
        } finally {
            if (n) throw s;
        }
    }
    return i;
}

function _arrayWithHoles(t) {
    if (Array.isArray(t)) return t;
}

function _objectSpread(e) {
    for (var t = 1; t < arguments.length; t++) {
        var i = null != arguments[t] ? arguments[t] : {}, a = Object.keys(i);
        "function" == typeof Object.getOwnPropertySymbols && (a = a.concat(Object.getOwnPropertySymbols(i).filter(function(t) {
            return Object.getOwnPropertyDescriptor(i, t).enumerable;
        }))), a.forEach(function(t) {
            _defineProperty(e, t, i[t]);
        });
    }
    return e;
}

function _defineProperty(t, e, i) {
    return e in t ? Object.defineProperty(t, e, {
        value: i,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : t[e] = i, t;
}

function _toConsumableArray(t) {
    return _arrayWithoutHoles(t) || _iterableToArray(t) || _nonIterableSpread();
}

function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _iterableToArray(t) {
    if (Symbol.iterator in Object(t) || "[object Arguments]" === Object.prototype.toString.call(t)) return Array.from(t);
}

function _arrayWithoutHoles(t) {
    if (Array.isArray(t)) {
        for (var e = 0, i = new Array(t.length); e < t.length; e++) i[e] = t[e];
        return i;
    }
}

var app = getApp(), LIMIT = 20, maxCount = 99, FILTER_LABEL = {
    chattype: [ {
        name: "已联系",
        id: 1
    }, {
        name: "未联系",
        id: 2
    }, {
        name: "未读消息",
        id: 3
    } ],
    clienttype: [ {
        name: "未分类",
        id: 1
    }, {
        name: "已转为客户",
        id: 2
    } ]
};

Component({
    options: {
        multipleSlots: !0
    },
    externalClasses: [ "niche-menu-custom", "screen-modal-custom" ],
    properties: {
        guid: String,
        card: Object,
        switchPostion: {
            type: Boolean,
            value: !0
        },
        positionStyle: String,
        lazy: {
            type: Boolean,
            value: !1
        },
        BAR_HEIGHT: String
    },
    data: {
        chatLists: Array(8).fill({
            desc: "1",
            content: {
                content: 1
            }
        }),
        filter: {
            types: {
                chattype: 0,
                clienttype: 0
            }
        },
        search: {},
        FILTER_LABEL: FILTER_LABEL,
        showSkeleton: !0
    },
    created: function() {
        this.initEvents();
    },
    ready: function() {
        this.initData(), this.data.lazy || this.init();
    },
    detached: function() {
        this.$events && this.$events.forEach(function(t) {
            return _eventEmitter.default.removeListener.apply(_eventEmitter.default, _toConsumableArray(t));
        });
    },
    methods: {
        initData: function() {
            this.unreadsDistancesGroup = [], this.takeTurnsIndex = 0, this.allUnreads = 0, this.setUnreadCount();
        },
        init: function() {
            try {
                this.selectComponent("#skeleton").create(this);
            } catch (t) {}
            this.getLists(!0, wx.hideLoading);
        },
        initEvents: function() {
            var t = this;
            this.$events = [ [ "chat.lists.change", this.getLists.bind(this, !0) ], [ "radar.message.socket", this.handleSocket.bind(this) ], [ "chat.sendmsg", this.chatRoomSyn.bind(this) ], [ "chat.empty.reads", this.emptyChatReads.bind(this) ], [ "radar.unreads.change", function() {
                return t.setUnreadCount();
            } ] ], this.$events.forEach(function(t) {
                return _eventEmitter.default.addListener.apply(_eventEmitter.default, _toConsumableArray(t));
            });
        },
        setUnreadCount: function() {
            var t = app.globalData.radarCount || 0;
            this.setData({
                count: maxCount < t ? "99+" : t
            });
        },
        onPullDownRefresh: function() {
            this.getLists(!0, wx.stopPullDownRefresh);
        },
        onReachBottom: function() {
            var t = this;
            this.data.noMore || this.clickPostion || (this.setData({
                loadingMore: !0
            }), this.getLists(!1, function() {
                return t.setData({
                    loadingMore: !1
                });
            }));
        },
        getLists: function(i, t, a) {
            var e, n = this, s = this.data.chatLists || [];
            e = i ? parseInt(Date.now() / 1e3, 0) + 1e3 : s[s.length - 1].updatetime;
            var r = this.data, o = r.filter, c = o.chattype, h = o.clienttype, l = r.search.keyword, d = void 0 === l ? "" : l;
            _api2.default.chat.chat.chatlists({
                data: {
                    timestamp: e,
                    limit: LIMIT,
                    keyword: d,
                    guid: this.data.guid || "",
                    chattype: 0 < c ? c : 0,
                    clienttype: 0 < h ? h : 0
                },
                complete: t
            }).then(function(t) {
                var e = t.data.lists;
                return n.handleLists(e, a, i);
            });
        },
        handleLists: function(t, e, i) {
            t.forEach(function(t) {
                t.time = _util.default.formatTimeStamp(1e3 * t.updatetime);
            });
            var a = {
                noMore: t.length < LIMIT
            };
            if (i) a.showSkeleton = !1, a.chatLists = t; else {
                var n = (this.data.chatLists || []).length;
                t.forEach(function(t, e) {
                    a["chatLists[".concat(n + e, "]")] = t;
                });
            }
            this.setData(a), t.length && this.resetPositionUnreads(e);
        },
        handleSocket: function(e) {
            var t = this.data.chatLists;
            e.updatetime = e.createtime, e.time = "刚刚";
            var i = t.findIndex(function(t) {
                return +t.chatid == +e.chatid;
            });
            if (1 == +e.issystem) -1 < i && this.setData(_defineProperty({}, "chatLists[".concat(i, "]"), e)); else {
                if (-1 < i) {
                    e.unreads = t[i].unreads + 1;
                    var a = t.splice(i, 1);
                    e.desc = a[0].desc;
                } else e.unreads = 1;
                t.unshift(e), this.setData({
                    chatLists: t
                }), this.resetPositionUnreads();
            }
        },
        chatRoomSyn: function(e) {
            var t = this.data.chatLists, i = _objectSpread({}, e), a = t.findIndex(function(t) {
                return +e.chatid == +t.chatid;
            });
            -1 < a && ((i = t.splice(a, 1)[0]).content = e.content, i.updatetime = e.updatetime, 
            i.time = "刚刚"), t.unshift(i), this.setData({
                chatLists: t
            }), this.resetPositionUnreads();
        },
        emptyChatReads: function(e) {
            var t = this.data.chatLists.findIndex(function(t) {
                return +e == +t.chatid;
            });
            -1 < t && (this.setData(_defineProperty({}, "chatLists[".concat(t, "].unreads"), 0)), 
            this.resetPositionUnreads());
        },
        goChat: function(t) {
            var e = t.currentTarget.dataset.index, i = this.data, a = i.card, n = i.chatLists[e], s = n.desc, r = void 0 === s ? "" : s, o = n.realname, c = void 0 === o ? "" : o, h = n.chatid, l = n.uid, d = a ? a.cardid : "";
            this.$route("/publicPackage/salesradar/minichat/minichat", {
                index: e,
                chatid: h,
                cardid: d,
                touid: l,
                name: encodeURIComponent(c || ""),
                desc: encodeURIComponent(r || "")
            });
        },
        deleteChatTip: function(e) {
            var i = this;
            wx.showModal({
                content: "确认删除该聊天？",
                confirmColor: "#e94f4f",
                confirmText: "删除",
                success: function(t) {
                    t.confirm && i.deleteChat(e);
                }
            });
        },
        deleteChat: function(t) {
            var e = this, i = this.data.chatLists;
            wx.showLoading(), _api2.default.chat.chat.delete({
                data: {
                    chatid: i[t].chatid
                },
                complete: wx.hideLoading
            }).then(function() {
                e.$digest(), i.splice(t, 1), e.setData({
                    chatLists: i
                });
            });
        },
        getUnreadList: function() {
            return this.data.chatLists.filter(function(t) {
                return t.unreads;
            });
        },
        resetPositionUnreads: function(t) {},
        loadNewChatlistPostion: function() {
            var t = this;
            return !(this.data.count > this.allUnreads) || (clearTimeout(this.getUnreadsList), 
            this.getUnreadsList = setTimeout(function() {
                t.getLists(!1, function() {}, !0), clearTimeout(t.getUnreadsList);
            }, 200), !1);
        },
        positionUnreads: function() {
            var t = this.unreadsDistancesGroup;
            this.loadNewChatlistPostion() && (t.length ? Promise.resolve(t) : this.calcPositionDistance()).then(this.movePostion.bind(this));
        },
        movePostion: function(t) {
            var e = this.takeTurnsIndex;
            this.clickPostion = !0, wx.pageScrollTo({
                scrollTop: t[e] - 160,
                duration: 200
            }), this.resetPageScrollStatus(), this.takeTurnsIndex = (e + 1) % t.length;
        },
        resetPageScrollStatus: function() {
            var t = this;
            clearTimeout(this.isClickPostion), this.isClickPostion = setTimeout(function() {
                t.clickPostion = !1, clearTimeout(t.isClickPostion);
            }, 300);
        },
        calcPositionDistance: function() {
            var e = this, t = this.getUnreadList().map(function(t) {
                return t.chatid;
            }).map(function(t) {
                return e.getNodeScroll(t);
            });
            return Promise.all(t).then(function(t) {
                return e.unreadsDistancesGroup = t;
            });
        },
        getNodeScroll: function(e) {
            var i = this;
            return new Promise(function(n) {
                var t = wx.createSelectorQuery().in(i);
                t.select("#chatid".concat(e)).boundingClientRect(), t.selectViewport().scrollOffset(), 
                t.exec(function(t) {
                    var e = _slicedToArray(t, 2), i = e[0], a = e[1];
                    return n(i.top + a.scrollTop);
                });
            });
        },
        showLoading: function() {
            var t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : "";
            wx.showLoading({
                title: t,
                mask: !0
            });
        },
        tiggerScreenModal: function() {
            this.setData({
                "filter.modalShow": !this.data.filter.modalShow
            });
        },
        hideScreen: function() {
            if (this.data.filter.isfilter) return this.setData({
                "filter.modalShow": !1
            }), void (this.isSelected && this.resetSelect());
            this.handleHideScreen();
        },
        tiggerSearch: function(t) {
            var e = t.detail.inputShowed;
            this.cancelSearch(), this.data.filter.isfilter ? this.setData({
                "filter.modalShow": !1,
                "search.inputShowed": e
            }) : (this.setData({
                "search.inputShowed": e
            }), this.handleHideScreen());
        },
        cancelSearch: function(t) {
            !t && this.data.search.isSearch && (this.setData({
                "search.keyword": "",
                "search.isSearch": !1
            }), this.showLoading(), this.getLists(!0, wx.hideLoading));
        },
        onSearch: function(t) {
            var e = t.detail.value;
            this.showLoading("搜索中..."), this.setData({
                "search.keyword": e,
                "search.isSearch": !0,
                "filter.modalShow": !1
            }), this.getLists(!0, wx.hideLoading);
        },
        selectRadio: function(t) {
            var e = t.detail, i = this.data.filter;
            this.isSelected = !0, this.setData({
                filter: Object.assign(i, e)
            });
        },
        showAllList: function() {
            var t = this.data.filter.isfilter, e = this.data.search.isSearch;
            this.setData({
                "search.keyword": "",
                "search.inputShowed": !1,
                "filter.types": {
                    chattype: 0,
                    clienttype: 0
                }
            }), this.handleHideScreen(!0), (t || e) && (this.showLoading(), this.getLists(!0, wx.hideLoading));
        },
        resetSelect: function() {
            var e = this, t = Object.keys(FILTER_LABEL), i = this.data.filter.types;
            t.forEach(function(t) {
                e.selectComponent("#".concat(t)).resetSelect(i[t]);
            }), this.isSelected = !1;
        },
        handleHideScreen: function(t) {
            this.setData({
                "filter.isfilter": !1,
                "search.isSearch": !1,
                "filter.modalShow": !1,
                "filter.chattype": 0,
                "filter.clienttype": 0
            }), (this.isSelected || t) && this.resetSelect();
        },
        massCall: function() {
            var t = getCurrentPages().slice(-1)[0];
            if ("pages/radar/index/index" === t.route) {
                var e = t.data.card.isFeeVer ? "masslists" : "intro";
                this.$report("tabbar_radar_chat_masscall"), this.$route("/publicPackage/salesradar/settings/".concat(e, "/").concat(e, "?guid=").concat(this.data.guid, "&mode=mass"));
            }
        },
        confirmFilter: function() {
            var t = this.data.filter, e = t.chattype, i = t.clienttype, a = t.types;
            if (e === a.chattype && i === a.clienttype) return this.setData({
                "filter.modalShow": !1
            });
            this.setData({
                "filter.isfilter": !0,
                "filter.modalShow": !1,
                "filter.types": {
                    chattype: e,
                    clienttype: i
                }
            }), this.showLoading("筛选中..."), this.getLists(!0, wx.hideLoading);
        },
        onCellSwipe: function(t) {
            var e = t.detail, i = e.method, a = e.index;
            this[i](a);
        },
        showRemark: function(t) {
            var e = this.data.chatLists[t], i = e.chatid, a = e.uid, n = e.desc, s = e.realname;
            this.remarkIndex = t, this.dialog || (this.dialog = this.selectComponent("#chatSetRemark")), 
            this.dialog.toggle(!0, {
                chatid: i,
                uid: a,
                desc: n || s,
                realname: s
            });
        },
        setRemark: function(t) {
            var e = t.detail, i = this.data.chatLists, a = this.remarkIndex, n = i[a].realname;
            this.setData(_defineProperty({}, "chatLists[".concat(a, "].desc"), e || n)), _eventEmitter.default.emit("update.globalData.remark");
        }
    }
});